package com.sise.rsc.controller;

import com.sise.rsc.bean.Result;
import com.sise.rsc.dao.RedisDao;
import com.sise.rsc.entity.*;
import com.sise.rsc.service.*;
import com.sise.rsc.util.CacheUtil;
import com.sise.rsc.util.RandomUtil;
import com.sise.rsc.util.TimeUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/customer")
public class CustomerController   {

    @Resource
    private CustomerService customerService;
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private PackageService packageService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RedisDao redisDao;
    @Resource
    private TaskService taskService;

    /**
     * 普通用户登录后的初始界面
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(Model model){
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        //获取用户信息
        User user = userService.findUserByUsername(auth.getName());
        int uid=user.getId();
        List<APackage> aPackageList=packageService.findAllAPackageByUserId(uid);
        model.addAttribute("aPackageList",aPackageList);

        model.addAttribute("s",new SimpleDateFormat("yyyyMMddHHmmss"));
        return "customer/index";
    }

    /**
     * 普通用户注册
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public Result register(String username, String password){
        //查询是否存在相同用户名
        com.sise.rsc.entity.User user = userService.findUserByUsername(username);
        if (user != null)
            return new Result(500,"用户名已经存在，请重新输入！");
        //查询ROLE_USER
        Role role = roleService.findRoleByAuthority("ROLE_USER");
        if (role == null){
            role = new Role("ROLE_USER");
            roleService.save(role);
        }
        //新建User对象,密码采用加密算法
        user = null;
        user = new com.sise.rsc.entity.User(username,passwordEncoder.encode(password));
        List<Role> roles = new LinkedList<>();
        //保存数据
        roles.add(role);
        user.setRoles(roles);
        userService.save(user);
        //成功返回result对象
        return new Result(200,"注册成功，请登录！");
    }

    /**
     * 用户寄件,保存寄件订单信息
     * @return
     */
    @RequestMapping("/send")
    public String send(){
        return "customer/send";
    }

    @RequestMapping("/addPackage")
    @ResponseBody
    public Result addPackage(APackage aPackage,int saveF,int saveT,String tipF,String tipT, HttpSession session){

        Map<String,Object> re = new HashMap<>();

        User user = (User) session.getAttribute("SESSION_USER");
        if (user == null)
            return new Result(500,"获取用户信息失败，请登录后再试！");

        //设置订单状态为：1 待快递员取件
        aPackage.setState(1);
        aPackage.setUser(user);
        aPackage.setCreateTime(new Date());
        // 指定格式化格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String pNo = "XF"+ RandomUtil.getRandomNumber(4) +sf.format(new Date());
        aPackage.setNo(pNo);
        packageService.save(aPackage);
        //把该订单加入缓存，存入redis 设置过期时间为24H
        CacheUtil.packageList.add("package:"+pNo);
        redisDao.setKey("package:"+pNo,"没取件",24L, TimeUnit.HOURS);
        //保存地址信息
        if (saveF == 1){
            Address from = new Address(aPackage.getSendName(),aPackage.getSendPhone(),aPackage.getSendAddress());
            from.setTip(tipF);
            from.setUser(user);
            customerService.saveAddress(from);
        }
        if (saveT ==1){
            Address to = new Address(aPackage.getReceiptName(),aPackage.getReceiptPhone(),aPackage.getReceiptAddress());
            to.setTip(tipT);
            to.setUser(user);
            customerService.saveAddress(to);
        }
        //判断当前时间是否为工作时间，确认是否分配取件任务 ，time:7-18
        Boolean flag = TimeUtil.belongCalendarIn6To18();

        if (flag){
            //在工作时间段，分配派件任务
            if (taskService.AssignTasks(aPackage,"取件")){
                //成功找到配送员
                Courier courier = taskService.findTaskByTaskNameAndStateAndAPackageNo(pNo,1,"取件").getCourier();
                System.out.println("package:" + pNo+" 成功分配取件快递员");
                re.put("p_id",aPackage.getId());
                re.put("c",courier);
                return new Result(200,"订单提交成功！"+courier.getRealName(),re);
            }else {
                //没有找到配送员
                //判断是否为可自动分配
                System.out.println("加入缓存：packageAutoList,等待快递员打卡状态为正常时触发，再去分配任务");
                if (taskService.isCanAutoAssignTasks(aPackage.getSendAddress())){
                    //是则加入缓存：packageAutoList,等待快递员打卡状态为正常时触发，再去分配任务
                    CacheUtil.packageAutoList.add(pNo);
                }
            }
        }else{
            //不在工作时间段，不分配派件任务,加入缓存隔天分配包裹列表
            System.out.println("不在工作时间段，不分配派件任务,加入缓存隔天分配包裹列表");
            CacheUtil.packageNextDayList.add(pNo);

        }
        re.put("p_id",aPackage.getId());
        return new Result(200,"订单提交成功！",re);
    }

    /**
     * 当前用户取消订单
     * @param packageId
     * @param session
     * @return
     */
    @RequestMapping("/cancelPackage")
    @ResponseBody
    public Result cancelPackage(int packageId,HttpSession session){

        APackage aPackage = packageService.findAPackageById(packageId);
        User user = (User) session.getAttribute("SESSION_USER");
        if (user == null)
            return new Result(500,"获取用户信息失败，请登录后再试！");
        if (aPackage.getUser().getId() != user.getId())
            return new Result(500,"取消订单失败，不是当前用户所提交的订单！");
        if (aPackage.getState() != 1)
            return new Result(500,"当前订单状态下，不允许取消订单！");
        //取消订单
        aPackage.setState(-1);
        packageService.updateAPackageState(aPackage);
        return new Result(200,"订单取消成功！");
    }

    //用户查找本人快递
    @RequestMapping("/search")
    public String searchPackage(HttpSession session,Model model){
        User user = (User) session.getAttribute("SESSION_USER");
        List<APackage> aPackageList=packageService.findAllAPackageByUserId(user.getId());
        model.addAttribute("aPackageList",aPackageList);
//        List<PackageAction> packageActionList=customerService.searchPackageActionByPackageNo(packageNo);
//        //如果没有任何动作，则重定向到客户主页面
//        if (packageActionList.isEmpty())
//            return "redirect:customer/index";
//        //加入model
//        model.addAttribute("packageActionList",packageActionList);
        return "customer/search-package-list";
    }
    //用户查找本人快递
    @RequestMapping("/searchPackageByPNo")
    public String searchPackageByPNo(Model model,String pno){
        List<PackageAction> packageActionList=customerService.searchPackageActionByPackageNo(pno);
        //如果没有任何动作，则重定向到客户主页面
        if (packageActionList.isEmpty())
            return "redirect:/customer/index";
        //加入model
        model.addAttribute("packageActionList",packageActionList);
        model.addAttribute("package",packageService.findAPackageByNo(pno));
        return "customer/search-package";
    }
}
